import pandas as pd
import os, glob, sys
import os.path as osp

file_path = os.path.abspath(__file__)
sys.path.append(os.path.abspath(os.path.join(file_path, "..", "..", "..", "..")))

from code_aculat.data_analyse.data_analyse_coco import show_bar, sorted_dict


def check_txt_not_in_csv_record():
    "查看txt文件夹中哪个文件不在csv的记录之中"
    csv_path = r"/home/data1/yw/mmdetection/data/water_detection/split_folds/fold_v1/test_right.csv"
    txt_dir = r"/home/data1/yw/mmdetection/data/water_detection/split_folds/fold_v1/yolo_txt_test"
    df = pd.read_csv(csv_path)

    # 获取dataframe对象的值赋给aa，而不是以dataframe形式去判断
    aa = df.values

    txt_list = os.listdir(txt_dir)

    print("len of aa {} and len of txt_list {}".format(aa.shape[0], len(txt_list)))
    for txt in txt_list:
        if txt.strip('.txt') not in aa:
            print(txt)


def check_category_num():
    "遍历txt文档，得到类别总数"
    origin_txt_dir = r"/Users/edy/Data/DB/label_data/data_split/data_foldv1/labels/val"
    cat_ids = []
    # 遍历所有val里的txt文件,找出所有包含这些类别的txt，然后全移动到train里
    for txt in glob.glob(os.path.join(origin_txt_dir, "*.txt")):
        with open(txt, 'r') as f:
            txt_obs = f.readlines()

        for obs in txt_obs:
            cate_id, _, _, _, _ = obs.strip('\n').split(' ')
            cate_id = int(cate_id)
            # if cate_id==0:   #用于寻找验证集缺少哪个类，然后把训练集里的这个文件移动进去
            #     print('ok')
            if cate_id not in cat_ids:
                cat_ids.append(cate_id)
    print("number of category is  %d" % len(cat_ids))


def get_obs_num_of_each_category():
    "遍历txt文件，获得每类下的实例数量"
    label_dir = r"/Users/edy/Data/RuPin/钻石碗/数据/BN_data/data_split/data_foldv1/labels"
    label_train = osp.join(label_dir, 'train')
    label_val = osp.join(label_dir, 'val')

    target_classes = ["依仑大白梨汽水500ml",
"依仑大连汽水500ml",
"依仑大连汽水桔子味500ml",
"依仑大连汽水苹果味500ml",
"依仑大连荔枝味碳酸饮料500ml",
"依仑小蜜蜂葡萄果味型碳酸饮料500ml",
"八王寺山楂香梨维生素果汁汽水380ml",
"八王寺荔枝维生素果汁汽水380ml",
"八王寺香橙维生素果汁汽水380ml",
"大窑嘉宾果味汽水520ml",
"大窑嘉宾果味汽水PET520ml",
"大窑橙诺520ml",
"大窑橙诺PET520ml",
"宏宝莱果汁鲜山楂味饮料玻璃瓶200ml",
"宏宝莱果汁鲜桔子味汽水饮料玻璃瓶200ml",
"宏宝莱果汁鲜脐橙味饮料玻璃瓶200ml",
"宏宝莱生榨山水蜜桃果味饮料300ml",
"宏宝莱生榨蓝莓苹果复合果味饮料300ml",
"宏宝莱生榨香橙果肉饮料300ml",
"宏宝莱老汽水550ml",
"宏宝莱花生露植物蛋白饮料445ml",
"宏宝莱花生露植物蛋白饮料玻璃瓶200ml",
"宏宝莱荔枝味汽水饮料玻璃瓶200ml",
"宏宝莱荔枝汽水330ml铝罐",
"旺仔大白梨果味型碳酸饮料310ml",
"珍珍桃味汽水330ml",
"珍珍桔味汽水330ml",
"珍珍荔枝味汽水330ml",
"秋林格瓦斯PE瓶350ml",
"秋林黑格瓦斯PE瓶350ml", ]
    target_classes=[]

    catid_to_name = {}

    class_txt = osp.join(label_dir, 'class_name_to_catid.txt')

    with open(class_txt, 'r') as f:
        records = f.readlines()

    for rec in records:
        cate_name, cate_id = rec.strip('\n').split('  ')
        print("%d: '%s' " % (int(cate_id), cate_name))  # 输出cate_id 和类名的对应关系，方便查找
        catid_to_name[int(cate_id)] = cate_name

    train_obs_num_dict = {}
    val_obs_num_dict = {}

    for txt in glob.glob(os.path.join(label_train, "*.txt")):
        with open(txt, 'r') as f:
            txt_obs = f.readlines()

        for obs in txt_obs:
            cate_id, _, _, _, _ = obs.strip('\n').split(' ')
            cate_id = int(cate_id)

            if cate_id not in train_obs_num_dict:
                train_obs_num_dict[cate_id] = 0
            train_obs_num_dict[cate_id] += 1

    for txt in glob.glob(os.path.join(label_val, "*.txt")):
        with open(txt, 'r') as f:
            txt_obs = f.readlines()

        for obs in txt_obs:
            cate_id, _, _, _, _ = obs.strip('\n').split(' ')
            cate_id = int(cate_id)

            if cate_id not in val_obs_num_dict:
                val_obs_num_dict[cate_id] = 0
            val_obs_num_dict[cate_id] += 1

    if len(target_classes):
        show_train_obs_num_dict = {}
        show_val_obs_num_dict = {}
        for id in train_obs_num_dict.keys():
            if catid_to_name[id] in target_classes:
                show_train_obs_num_dict[id] = train_obs_num_dict[id]
                # show_train_obs_num_dict[catid_to_name[id]]=train_obs_num_dict[id]

        for id in val_obs_num_dict.keys():
            if catid_to_name[id] in target_classes:
                show_val_obs_num_dict[id] = val_obs_num_dict[id]
                # show_val_obs_num_dict[catid_to_name[id]]=val_obs_num_dict[id]

        show_bar(sorted_dict(show_train_obs_num_dict))
        show_bar(sorted_dict(show_val_obs_num_dict))
    else:
        show_bar(sorted_dict(train_obs_num_dict))
        show_bar(sorted_dict(val_obs_num_dict))

def checkout_empty_txt():
    txt_dir=r"/Users/edy/Data/DB/yq10_db/data_split/data_foldv1/labels/train"

    for txt in os.listdir(txt_dir):
        if txt.split('.')[-1] =="txt":
            with open(osp.join(txt_dir,txt),'r') as f:
                record=f.readlines()

            if not len(record):
                print(txt)


if __name__ == "__main__":
    get_obs_num_of_each_category()
    # check_category_num()
    # checkout_empty_txt()
